import { defineStore } from 'pinia'
import { ref } from 'vue'
import { loginAPI, registerAPI, logoutAPI } from '@/api/userAPI'
import { ElMessage } from 'element-plus'

export const useUserStore = defineStore('user', () => {
  const id = ref<string | null>(localStorage.getItem('id'))
  const token = ref<string | null>(localStorage.getItem('token'))
  const username = ref<string | null>(localStorage.getItem('username'))
  const email = ref<string | null>(localStorage.getItem('email'))
  const isAuthorized = ref<boolean>(localStorage.getItem('isAuthorized') === 'true')

  function setUser(user: { id: string; token: string; username: string; email: string }) {
    id.value = user.id
    token.value = user.token
    username.value = user.username
    email.value = user.email
    isAuthorized.value = true
    localStorage.setItem('id', user.id)
    localStorage.setItem('token', user.token)
    localStorage.setItem('username', user.username)
    localStorage.setItem('email', user.email)
    localStorage.setItem('isAuthorized', 'true')
  }

  async function login(id: string, password: string) {
    try {
      const res = await loginAPI(id, password)
      if (res.code === 200) {
        setUser({
          id: res.data.user_id,
          token: res.data.token,
          username: res.data.username,
          email: res.data.user_email,
        })
        return true
      }
      return false
    } catch {
      return false
    }
  }

  async function register(id: string, username: string, password: string) {
    try {
      const res = await registerAPI(id, username, password)
      if (res.code === 200) {
        setUser({
          id: res.data.user_id,
          token: res.data.token,
          username: res.data.username,
          email: res.data.user_email,
        })
        return true
      }
      return false
    } catch {
      return false
    }
  }

  async function logout() {
    try {
      await logoutAPI(id.value || '', token.value || '')
      ElMessage.success('注销成功')
    } catch {
      //有可能会因为token过期导致失败，允许直接登出
      ElMessage.success('注销成功')
    }
    id.value = null
    token.value = null
    username.value = null
    email.value = null
    isAuthorized.value = false
    localStorage.removeItem('id')
    localStorage.removeItem('token')
    localStorage.removeItem('username')
    localStorage.removeItem('email')
    localStorage.removeItem('isAuthorized')
  }

  return { id, token, username, email, isAuthorized, setUser, login, register, logout }
})
